<?php
namespace App\Libs;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use App\Libs\TokenLibrary;
use Illuminate\Http\Request;
class SafeLibrary {
    private $no_verify_path=[
        'AboutController'=>'add',
    ];
    private $blackIp=[];
    private $user_type=2;//1. 后台用户   2 前台用户
    public function  __construct($user_type=''){
        $this->user_type=$user_type;
        $this->checkUserAgent();
        $this->checkBlackIp();
       // $this->checkIpTime();
       // $this->checkReferer();
        //$this->checkHttp();
        //var_dump($_REQUEST);exit;
        $this->insert_log();
    }

    /**
    * 此方法返回用户的IP地址，同时如果拥有代理IP，将会以逗号追加在后面
    * 如果只取用当前IP，可参考 ：
    * $ips = explode(',', $bargainModel->get_real_ips());
    * $ip = $ips[0];
    */
    public function get_real_ips(){
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP") , "unknown")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR") , "unknown")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR") , "unknown")) {
            $ip = getenv("REMOTE_ADDR");
        } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else if(getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR") , "unknown")){
            $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            if($ip != ""){
                $arr = explode(",",$ip);
                $ip=$arr[0];
            }else{
                $ip = "unknown";
            }   


        }else{
            $ip = "unknown";
        }

        return $ip;
    }

    /**
     * PHP 获取当前页面 URL
     * @return string
     */
    public function get_referer(){
        if(isset($_SERVER["HTTP_REFERER"])){
            $url = $_SERVER["HTTP_REFERER"]; //获取完整的来路URL
            $str = str_replace("http://","",$url); //去掉http://
            $strdomain = explode("/",$str); // 以“/”分开成数组
            $domain = $strdomain[0]; //取第一个“/”以前的字符
        }else{
            $domain = 'Unknown';
        }
        
        return $domain;
    }
    /**
     * 获取客户端操作系统信息包括 win10
     * @param  null
     * @author  Jea杨
     * @return string
     */
    public function getOS(){
        if(isset($_SERVER['HTTP_USER_AGENT'])){
            $agent = $_SERVER['HTTP_USER_AGENT'];
        }else{
            $os = 'Unknown';
            return $os;
        }
        
        $os = false;
        if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
            $os = 'Windows 95';
        } else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
            $os = 'Windows ME';
        } else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
            $os = 'Windows 98';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
            $os = 'Windows Vista';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
            $os = 'Windows 7';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
            $os = 'Windows 8';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
            $os = 'Windows 10';#添加win10判断
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
            $os = 'Windows XP';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
            $os = 'Windows 2000';
        } else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
            $os = 'Windows NT';
        } else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
            $os = 'Windows 32';
        } else if (preg_match('/linux/i', $agent)) {
            $os = 'Linux';
        } else if (preg_match('/unix/i', $agent)) {
            $os = 'Unix';
        } else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
            $os = 'SunOS';
        } else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
            $os = 'IBM OS/2';
        } else if (preg_match('/Mac/i', $agent) && preg_match('/PC/i', $agent)) {
            $os = 'Macintosh';
        } else if (preg_match('/PowerPC/i', $agent)) {
            $os = 'PowerPC';
        } else if (preg_match('/AIX/i', $agent)) {
            $os = 'AIX';
        } else if (preg_match('/HPUX/i', $agent)) {
            $os = 'HPUX';
        } else if (preg_match('/NetBSD/i', $agent)) {
            $os = 'NetBSD';
        } else if (preg_match('/BSD/i', $agent)) {
            $os = 'BSD';
        } else if (preg_match('/OSF1/i', $agent)) {
            $os = 'OSF1';
        } else if (preg_match('/IRIX/i', $agent)) {
            $os = 'IRIX';
        } else if (preg_match('/FreeBSD/i', $agent)) {
            $os = 'FreeBSD';
        } else if (preg_match('/teleport/i', $agent)) {
            $os = 'teleport';
        } else if (preg_match('/flashget/i', $agent)) {
            $os = 'flashget';
        } else if (preg_match('/webzip/i', $agent)) {
            $os = 'webzip';
        } else if (preg_match('/offline/i', $agent)) {
            $os = 'offline';
        } else {
            $os = 'Unknown';
        }
        return $os;
    }
    /**
     * 获取客户端浏览器信息
     * @param  null
     * @author  Jea杨
     * @return string
     */
    public function getBroswer(){
        
        if(isset($_SERVER['HTTP_USER_AGENT'])){
            $user_OSagent = $_SERVER['HTTP_USER_AGENT'];
        }else{
            return "Other Browser";
        }
        if (strpos($user_OSagent, "Maxthon") && strpos($user_OSagent, "MSIE")) {
            $visitor_browser = "Maxthon(Microsoft IE)";
        } elseif (strpos($user_OSagent, "Maxthon 2.0")) {
            $visitor_browser = "Maxthon 2.0";
        } elseif (strpos($user_OSagent, "Maxthon")) {
            $visitor_browser = "Maxthon";
        } elseif (strpos($user_OSagent, "Edge")) {
            $visitor_browser = "Edge";
        } elseif (strpos($user_OSagent, "Trident")) {
            $visitor_browser = "IE";
        } elseif (strpos($user_OSagent, "MSIE")) {
            $visitor_browser = "IE";
        } elseif (strpos($user_OSagent, "MSIE")) {
            $visitor_browser = "MSIE";
        } elseif (strpos($user_OSagent, "NetCaptor")) {
            $visitor_browser = "NetCaptor";
        } elseif (strpos($user_OSagent, "Netscape")) {
            $visitor_browser = "Netscape";
        } elseif (strpos($user_OSagent, "Chrome")) {
            $visitor_browser = "Chrome";
        } elseif (strpos($user_OSagent, "Lynx")) {
            $visitor_browser = "Lynx";
        } elseif (strpos($user_OSagent, "Opera")) {
            $visitor_browser = "Opera";
        } elseif (strpos($user_OSagent, "MicroMessenger")) {
            $visitor_browser = "WeiXinBrowser";
        } elseif (strpos($user_OSagent, "Konqueror")) {
            $visitor_browser = "Konqueror";
        } elseif (strpos($user_OSagent, "Mozilla/5.0")) {
            $visitor_browser = "Mozilla";
        } elseif (strpos($user_OSagent, "Firefox")) {
            $visitor_browser = "Firefox";
        } elseif (strpos($user_OSagent, "U")) {
            $visitor_browser = "Firefox";
        } else {
            $visitor_browser = "Other Browser";
        }
        return $visitor_browser;
    }

    #User-Agent检测
    public function  checkUserAgent()
    {
        $user_agent =$_SERVER['HTTP_USER_AGENT'];
        if (preg_match('/bot|crawl|slurp|spider/i',$user_agent))
        {
            $msg=[
                'code'=>'500',
                'msg'=>'HTTP/1.1 403 Forbidden'
            ];
            echo json_encode($msg);
            exit();
        }
    }

    # ip 黑名单

    public function checkBlackIp()
    {
        $ip =$_SERVER['REMOTE_ADDR'];
        if (in_array($ip, $this->blackIp))
        {
            $msg=[
                'code'=>'500',
                'msg'=>'HTTP/1.1 403 Forbidden'
            ];
            echo json_encode($msg);
            exit();
        }
    }

    #ip 检测时间
    public function checkIpTime()
    {
        session_start();
        $last_request_time =$_SESSION['last_request_time'];
        $current_time = time();
        if ($current_time -$last_request_time <1)
        {
            $msg=[
                'code'=>'500',
                'msg'=>'HTTP/1.1 403 Forbidden'
            ];
            echo json_encode($msg);
            exit();
        }
        $_SESSION['last_request_time']=$current_time;
    }

    # Referer检测
    public function checkReferer()
    {
        if (!isset($_SERVER['HTTP_REFERER'])){
            $msg=[
                'code'=>'500',
                'msg'=>'HTTP/1.1 403 Forbidden'
            ];
            echo json_encode($msg);
            exit();
        }
    }
    # HTTP
    public function checkHttp()
    {
        if (!empty($_SERVER['HTTP_COOKIE'])||!empty($_SERVER['HTTP_REFERER'])){     $msg=[
                'code'=>'500',
                'msg'=>'HTTP/1.1 403 Forbidden'
            ];
            echo json_encode($msg);
            exit();
        }
    }
    //访问路由地址
    public function path()
    {
        $route = Route::current();
        $controllerName = class_basename($route->getAction()['controller']);
        list($controller, $method) = explode('@', $controllerName);
        $controller_method=$controller.'/'.$method;
        return $controller_method;

    }
    //获取参数
    public function get_params()
    {


        if(isset($_SERVER['QUERY_STRING'])&&!empty($_SERVER['QUERY_STRING'])){
            $result=$_SERVER['QUERY_STRING'];

        }else{
            $result=$_REQUEST;
            if(empty($result)){
                $result=Request()->all();
            }
            if(empty($result)){
                $result='Unknown';
            }else{
                $result=http_build_query($result);
            }

            
            
        }
        //dd($result);
        return $result;
        
    }
    //获取url
    public  function get_REQUEST_URI()
    {
        if(isset($_SERVER['REQUEST_URI'])&&isset($_SERVER['SERVER_ADDR'])&&isset($_SERVER['SERVER_PORT'])&&isset($_SERVER['REQUEST_SCHEME'])){
            $SERVER_ADDR=$_SERVER['SERVER_ADDR'];
            $SERVER_PORT=$_SERVER['SERVER_PORT'];
            $REQUEST_URI=$_SERVER['REQUEST_URI'];
            $REQUEST_SCHEME=$_SERVER['REQUEST_SCHEME'];
            $result="$REQUEST_SCHEME://$SERVER_ADDR:$SERVER_PORT$REQUEST_URI";
        }else{
            $result='Unknown';
        }
        return $result;
        
    }
    //请求方式
    public function get_REQUEST_METHOD()
    {
        if(isset($_SERVER['REQUEST_METHOD'])){
            $result=$_SERVER['REQUEST_METHOD'];
        }else{
            $result='Unknown';
        }
        return $result;
        
    }
    //插入信息
    public function insert_log()
    {
        $path=$this->path();
        if(in_array($path,$this->no_verify_path)){
            return false;
        }

        $params=$this->get_params();
        $REQUEST_URI=$this->get_REQUEST_URI();
        $REQUEST_METHOD=$this->get_REQUEST_METHOD();
        if(isset($_SERVER['HTTP_ACCESSTOKEN'])&&!empty($_SERVER['HTTP_ACCESSTOKEN'])){
            $token=$_SERVER['HTTP_ACCESSTOKEN'];
            $tokeninfo=TokenLibrary::getTokenInfo($token);
        }else{
            $tokeninfo=false;
        }
        $admin_id=0;
        $phone=0;
        $admin_name=0;
        $type=$this->user_type;
        $path=$this->path();
        $ip=$this->get_real_ips();
        $referer=$this->get_referer();
        $os=$this->getOS();
        $browser=$this->getBroswer();
        $user_agent=$_SERVER['HTTP_USER_AGENT'];
        $create_time=time();
        
        if($tokeninfo!=false){

        
        $admin_id=$id=$tokeninfo->data->user_id;
  
        //dd($path);
        $phone='';
        $admin_name='';
        if($type==1){
            $info=DB::connection('mysql')->select("SELECT `username`,`mobile` FROM `sls_admin` where id='$id'");
            if($info){
                $info=(array)$info[0];
            }
            if(isset($info['mobile'])){
                $phone=$info['mobile'];
            }
            if(isset($info['username'])){
                $admin_name=$info['username'];
            }


        }else{
            $info=DB::connection('mysql_erp')->select("SELECT `name`,`telephone` FROM `sls_user` where id='$id'");
            if($info){
                $info=(array)$info[0];
            }
            if(isset($info['telephone'])){
                $phone=$info['telephone'];
            }
            if(isset($info['name'])){
                $admin_name=$info['name'];
            }

            //dd($info);
        }
        DB::connection('mysql')->insert('INSERT INTO `sls_admin_log` (`admin_id`, `phone`,`admin_name`,`path`,`ip`,`referer`,`os`,`browser`,`type`,`user_agent`,`create_time`,`params`,`REQUEST_URI`,`REQUEST_METHOD`) VALUES (?, ?,?, ?, ?, ?, ?, ?,?, ?, ?,?, ?, ?)', [$admin_id,$phone,$admin_name,$path,$ip,$referer,$os,$browser,$type,
            $user_agent,$create_time,$params,$REQUEST_URI,$REQUEST_METHOD]);

    }else{
        DB::connection('mysql')->insert('INSERT INTO `sls_admin_log` (`admin_id`, `phone`,`admin_name`,`path`,`ip`,`referer`,`os`,`browser`,`type`,`user_agent`,`create_time`,`params`,`REQUEST_URI`,`REQUEST_METHOD`) VALUES (?, ?,?, ?, ?, ?, ?, ?,?, ?, ?,?, ?, ?)', [$admin_id,$phone,$admin_name,$path,$ip,$referer,$os,$browser,$type,
            $user_agent,$create_time,$params,$REQUEST_URI,$REQUEST_METHOD]);
    }

    }

    
}
